package hjj.controller;



import hjj.entity.Product;
import hjj.feign.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    //注入restTemplate对象
    //@Autowired
    //private RestTemplate restTemplate;

    //springCloud提供的获取元数据的工具类
    @Autowired
    private DiscoveryClient discoveryClient;


    @Resource
    private ProductFeignClient productFeignClient;


    @RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
    public Product findById(@PathVariable Long id){
        //基于Feign组件调用远程微服务
        Product product = null;
        product = productFeignClient.findById(id);
        return product;
    }

    /*
    @RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
    public Product findById(@PathVariable Long id){
        //基于ribbon的形式调用远程微服务
        Product product = null;
        product = restTemplate.getForObject("http://service-product/product/1",Product.class);
        return product;
    }
    */

    /*
    @RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
    public Product findById(@PathVariable Long id){
        //基于discoveryClient.getInstances方法获取元数据
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        Product product = null;
        product = restTemplate.getForObject("http://"+instance.getHost()+":"+instance.getPort()+"/product/1",Product.class);
        System.out.println(product);
        return product;
    }
    */
}
